package com.gooluke.datasource;

import com.gooluke.config.DataSourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author gooluke
 * 将数据源信息存放至ThreadLocal
 */
public class DatasourceContextHolder {
    private static final Logger log = LoggerFactory.getLogger(DatasourceContextHolder.class);

    private static final ThreadLocal<String> DATASOURCE_THREAD_LOCAL = new ThreadLocal<>();

    public static void setDatasource(String datasource) {
        if (datasource != null && DataSourceConfig.dataSources.get(datasource) == null) {
            String errorMsg = String.format("数据源[%s]未配置", datasource);
            log.error(errorMsg);
            throw new RuntimeException(errorMsg);
        }
        DATASOURCE_THREAD_LOCAL.set(datasource);
    }

    public static String getDatasource() {
        return DATASOURCE_THREAD_LOCAL.get();
    }

    public static void clearDatasource() {
        DATASOURCE_THREAD_LOCAL.remove();
    }
}
